package com.cherry.mvc.controller;

import com.cherry.mvc.protype.HttpResult;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(path = "/upload")
public class UploadFileController {

    @RequestMapping("/remoteUpload")
    public String mvcUpload(MultipartFile upload, Model model) throws Exception {

        // 定义上传文件服务器路径
        String path = "http://localhost:9090/upload/";

        String fileName = generateServiceFileName(upload.getOriginalFilename());
// 创建客户端的对象
        Client client = Client.create();

        // 和图片服务器进行连接
        WebResource webResource = client.resource(path + fileName);

        // 上传文件
        webResource.put(upload.getBytes());

        model.addAttribute("fileName", fileName);
        return "upload_success";
    }


    /**
     * springMVC上传文件必须在配置文件中注入上传的配置
     *
     * @param request
     * @param upload
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/mvcUpload")
    public String mvcUpload(HttpServletRequest request, MultipartFile upload, Model model) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("/upload");
        Map map = request.getParameterMap();
        map.forEach((key, value) -> {
                System.out.println("key:" + key + ",value:" + Arrays.toString(((String[]) value)));
        });
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String fileName = generateServiceFileName(upload.getOriginalFilename());
        File file = new File(dir, fileName);
        System.out.println(file.getAbsolutePath());
        upload.transferTo(file);
        model.addAttribute("fileName", fileName);
        return "upload_success";
    }


    /**
     *
     * @param request
     * @param uploads  单个的话直接一个对象即可
     * @return
     * @throws Exception
     */
    @RequestMapping("/clientUpload1")
    @ResponseBody
    public HttpResult clientUpload1(HttpServletRequest request, @RequestPart("file") MultipartFile[] uploads) throws Exception {
        Map map = request.getParameterMap();
        map.forEach((key, value) -> {
            System.out.println("key:" + key + ",value:" + Arrays.toString(((String[]) value)));
        });
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        for (MultipartFile upload : uploads) {
            String fileName = generateServiceFileName(upload.getOriginalFilename());
            File file = new File(dir, fileName);
            System.out.println(file.getAbsolutePath());
            upload.transferTo(file);
        }
        return new HttpResult(null,200,"success");
    }

    @Deprecated
    @RequestMapping("/deprecatedUpload")
    public String deprecatedUpload(HttpServletRequest request, Model model) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
        List<FileItem> items = fileUpload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                //普通表单
                System.out.println(item.getFieldName());
//                + "=========" + item.getString(item.getFieldName()));
            } else {
                //文件表单
                String fileName = generateServiceFileName(item.getName());
                File file = new File(dir, fileName);
                item.write(file);
                //删除临时文件
                item.delete();
                model.addAttribute("fileName", fileName);
            }
        }
        return "upload_success";

    }

    private String generateServiceFileName(String fileName) {
        String uuid = UUID.randomUUID().toString();
        return uuid + "_" + fileName;
    }

}
